<template>
  <el-dialog
    :model-value="visible"
    :title="mode === 'create' ? '新增轮播图' : '编辑轮播图'"
    width="600px"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
      @submit.prevent
    >
      <el-form-item label="轮播图标题" prop="title">
        <el-input
          v-model="form.title"
          placeholder="请输入轮播图标题"
          maxlength="50"
          show-word-limit
        />
      </el-form-item>

      <el-form-item label="跳转链接" prop="link">
        <el-input
          v-model="form.link"
          placeholder="请输入跳转链接，如：/products/1 或 https://example.com"
        />
      </el-form-item>

      <el-form-item label="轮播图图片" prop="imageUrl">
        <div class="image-upload">
          <div class="upload-container">
            <div v-if="form.imageUrl" class="image-preview">
              <el-image
                :src="form.imageUrl"
                :preview-src-list="[form.imageUrl]"
                fit="cover"
                style="width: 100%; height: 200px; border-radius: 8px"
              />
              <div class="image-overlay">
                <el-icon><ZoomIn /></el-icon>
                <span>更换图片</span>
              </div>
            </div>
            <div v-else class="upload-placeholder" @click="handleImageUpload">
              <el-icon class="upload-icon"><Plus /></el-icon>
              <div class="upload-text">点击上传图片</div>
              <div class="upload-tip">建议尺寸：750x300px，支持JPG、PNG格式</div>
            </div>
          </div>
          <input
            ref="imageInput"
            type="file"
            accept="image/*"
            style="display: none"
            @change="handleImageChange"
          />
        </div>
      </el-form-item>

      <el-form-item label="生效时间" prop="timeRange">
        <el-date-picker
          v-model="form.timeRange"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
          style="width: 100%"
        />
        <div class="form-tip">不设置则立即生效，永久有效</div>
      </el-form-item>

      <el-form-item label="排序" prop="sort">
        <el-input-number
          v-model="form.sort"
          :min="1"
          :max="999"
          controls-position="right"
          style="width: 100%"
        />
        <div class="form-tip">数值越小显示越靠前</div>
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="form.status">
          <el-radio :label="1">启用</el-radio>
          <el-radio :label="0">禁用</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="备注">
        <el-input
          v-model="form.remark"
          type="textarea"
          :rows="3"
          placeholder="请输入备注信息"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" :loading="loading" @click="handleSubmit">
          {{ mode === 'create' ? '创建' : '更新' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus, ZoomIn } from '@element-plus/icons-vue'
import { carouselAPI } from '@/api/banner'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  mode: {
    type: String,
    default: 'create',
    validator: (value) => ['create', 'edit'].includes(value)
  },
  data: {
    type: Object,
    default: null
  }
})

const emit = defineEmits(['update:visible', 'success'])

// 响应式数据
const formRef = ref()
const imageInput = ref()
const loading = ref(false)

const form = reactive({
  title: '',
  link: '',
  imageUrl: '',
  timeRange: [],
  sort: 1,
  status: 1,
  remark: ''
})

const rules = {
  title: [
    { required: true, message: '请输入轮播图标题', trigger: 'blur' },
    { min: 1, max: 50, message: '标题长度为1-50个字符', trigger: 'blur' }
  ],
  link: [
    { required: true, message: '请输入跳转链接', trigger: 'blur' }
  ],
  imageUrl: [
    { required: true, message: '请上传轮播图图片', trigger: 'change' }
  ],
  sort: [
    { required: true, message: '请输入排序值', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 上传配置
const uploadAction = computed(() => {
  return '/api/banners/upload'
})

// 图片上传前检查
const beforeImageUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过2MB!')
    return false
  }
  return true
}

// 处理图片上传点击
const handleImageUpload = () => {
  imageInput.value?.click()
}

// 处理图片选择
const handleImageChange = (event) => {
  const file = event.target.files[0]
  if (file) {
    const reader = new FileReader()
    reader.onload = (e) => {
      form.imageUrl = e.target.result
    }
    reader.readAsDataURL(file)
  }
  event.target.value = ''
}

// 监听props变化
watch(() => props.visible, (visible) => {
  if (visible) {
    if (props.mode === 'edit' && props.data) {
      // 编辑模式，填充表单数据
      Object.assign(form, {
        title: props.data.title || '',
        link: props.data.link || '',
        imageUrl: props.data.imageUrl || '',
        timeRange: props.data.startTime && props.data.endTime
          ? [props.data.startTime, props.data.endTime]
          : [],
        sort: props.data.sort || 1,
        status: props.data.status ?? 1,
        remark: props.data.remark || ''
      })
    } else {
      // 新增模式，重置表单
      resetForm()
    }
  }
})

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    title: '',
    link: '',
    imageUrl: '',
    timeRange: [],
    sort: 1,
    status: 1,
    remark: ''
  })
  formRef.value?.clearValidate()
}

// 关闭对话框
const handleClose = () => {
  emit('update:visible', false)
  resetForm()
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    const valid = await formRef.value.validate()
    if (!valid) return

    loading.value = true

    const submitData = {
      title: form.title,
      link: form.link,
      imageUrl: form.imageUrl,
      status: form.status,
      sort: form.sort,
      remark: form.remark
    }

    // 处理时间范围
    if (form.timeRange && form.timeRange.length === 2) {
      submitData.startTime = form.timeRange[0]
      submitData.endTime = form.timeRange[1]
    }

    if (props.mode === 'create') {
      await carouselAPI.create(submitData)
      ElMessage.success('轮播图创建成功')
    } else {
      await carouselAPI.update(props.data.id, submitData)
      ElMessage.success('轮播图更新成功')
    }

    emit('success')
  } catch (error) {
    console.error('保存轮播图失败:', error)
    ElMessage.error(error.message || '保存失败')
  } finally {
    loading.value = false
  }
}
</script>

<style lang="scss" scoped>
.image-upload {
  .upload-container {
    width: 100%;
    max-width: 500px;
  }

  .image-preview {
    width: 100%;
    position: relative;
    overflow: hidden;
    border-radius: 8px;

    .el-image {
      display: block;
    }

    .image-overlay {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: rgba(0, 0, 0, 0.5);
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      color: white;
      opacity: 0;
      transition: opacity 0.3s;

      &:hover {
        opacity: 1;
      }

      .el-icon {
        font-size: 24px;
        margin-bottom: 8px;
      }

      span {
        font-size: 14px;
      }
    }
  }

  .upload-placeholder {
    width: 100%;
    height: 200px;
    border: 2px dashed #d9d9d9;
    border-radius: 8px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: all 0.3s;

    &:hover {
      border-color: #409eff;
    }

    .upload-icon {
      font-size: 32px;
      color: #8c939d;
      margin-bottom: 8px;
    }

    .upload-text {
      font-size: 16px;
      color: #606266;
      margin-bottom: 4px;
    }

    .upload-tip {
      font-size: 12px;
      color: #909399;
    }
  }
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
  line-height: 1.4;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>